﻿#!/usr/bin/python

import os
import sys

tool_version	=	"1.0"
tmpResult = "tmpResult"

def popenLog(str = ""):
    os.popen(str + ";")
    print(str + "\n")

def run():
	SrvIP="127.0.0.1"
	NeedHwVersion=""
	NeedSwVersion=""
	NowSwVersion=""
	FPGAType=""
	ProductDir=""
	InstallDir=""
	UserDir=""
	NewInstall=0	

	# 解析参数
	execResultStrV=getExecResultStrV("rem_install.conf")
	for line in range(0, len(execResultStrV)):
		lineStr=str(execResultStrV[line])
		# 空或注释直接跳过
		if lineStr == "" or lineStr.find("#")>=0:
			continue

		if lineStr.find("REM_VERSION=") >= 0:
			NeedSwVersion = lineStr.split("=",1)[1][0:-1]
			print("升级软件版本:" +NeedSwVersion)

		if lineStr.find("REM_HW_VERSION=") >= 0:
			NeedHwVersion = lineStr.split("=",1)[1][0:-1]
			print("升级硬件版本:" +NeedHwVersion )

		if lineStr.find("NOW_VERSION=") >= 0:
			NowSwVersion= lineStr.split("=",1)[1][0:-1]
			print("当前软件版本:" + NowSwVersion)

		if lineStr.find("NEW_INSTALL=") >= 0:
			NewInstall=lineStr.split("=",1)[1][0:-1]
			print("当前执行模式:" + NewInstall)

		if lineStr.find("DB_IP=")>= 0:
			SrvIP = lineStr.split("=",1)[1][0:-1]
			print("IP地址:" + SrvIP)

		if lineStr.find("REM_DIR=")>= 0:
			ProductDir = UserDir +"/"+lineStr.split("/",1)[1][0:-1]
			print("主目录:" + ProductDir)
		
		if lineStr.find("USER_DIR=")>= 0:
			UserDir = lineStr.split("=",1)[1][0:-1]
			print("用户目录:" +UserDir)

		if lineStr.find("INST_INSTALL_PACKAGE=") >= 0:
			InstallDir =UserDir+"/"+lineStr.split("/",1)[1][0:-1]
			print("安装源目录:"+InstallDir )

	# 升级数据库 2 和3 效果一样
        if "2" == NewInstall or "3" == NewInstall or "4" == NewInstall:
		dbParamUpdate(type=NewInstall, needSwVersion=NeedSwVersion, nowSwVersion=NowSwVersion, installDir=InstallDir, srvIP ="127.0.0.1")
	
	if "3" == NewInstall or "4" == NewInstall:
		upHW(hwVersion=NeedHwVersion, productDir=ProductDir, installDir=InstallDir)

def upHW(hwVersion="", productDir="", installDir=""):
	# 中间输出文件
	tmpResult = "tmpResult"
	# 重定向结果文件
	if("" == hwVersion):
		print("warn hw file conf is empty, can not update hw")
		return

	# 拉低 # 支持后续产品 例如rem_two rem_three
	print("--------停止主服务--------") 
	popenLog(productDir + "/stop_primary.sh")
	popenLog("cd " + productDir + "/driver; chmod +x *; ./unload_driver")
	print("--------卸载驱动--------")
	popenLog("cd /home/user0/pcie_cfg; chmod +x *; ./run_driver")
	print("--------拉低板卡--------")
	popenLog("lspci |grep Eth > tmpResult")
	popenLog("cat tmpResult")
	execResultLines=getExecResultStrV(tmpResult)

	if findKeyInfo(execResultLines, "rev ff") < 0:
		# 拉低失败
		print(tmpResult)
		g_log.log("error set fpga sig low failed can not update hw")
		return

	# 升级硬件
	print("--------移除旧硬件版本:mv *.xof ../--------")
	popenLog("cd /home/user0/hwfile_for_burn/xof/; mv *.xof ../")
	print("--------拷贝硬件升级文件:" + hwVersion+"--------")
	popenLog("cp " + installDir + "/" + hwVersion + " /home/user0/hwfile_for_burn/xof/; chmod +x /home/user0/hwfile_for_burn/*")
	# 获取usb配置
	print("--------配置usb--------")
	popenLog("/home/user0/intelFPGA/18.0/qprogrammer/bin/jtagconfig> tmpResult")
	execResultLines=getExecResultStrV(tmpResult)

	FPGAType = "mg5"
	for line in execResultLines:
		index = line.find("USB")
		if index >= 0:
			popenLog("echo " + line[index:-1] + " > /home/user0/hwfile_for_burn/FPGA_burn/usbblaster_name.txt")
		index = findKeyInfo(execResultLines, "A9")
		if index<0:
			FPGAType = "de5"
		print("板卡类型:" + FPGAType + " 请执行:./fpga_burn -m 1 -b " + FPGAType + " 进行升级")
		return
	

def dbParamUpdate(type ="0", needSwVersion="", nowSwVersion="",  installDir="", srvIP ="127.0.0.1"):
	sqlDir=""
	#升级
	if("0" == type):
		print("数据库配置升级模式错误:" + type + " 退出.")
		return

	if "2" == type or "3" == type:
		sqlDir = installDir + "/" + needSwVersion + "/server_setup_pack/fut_db_files/up_fut_db_files"
		popenLog("cd " + needSwVersion + "; unzip -o -q server_setup_pack.zip;cd -")
	#回退
	else:
		sqlDir = installDir + "/" + nowSwVersion + "/server_setup_pack/fut_db_files/back_fut_db_files"
		popenLog( "cd " + nowSwVersion + "; unzip -o -q server_setup_pack.zip; cd -")

	# 中间输出文件
	tmpResult="tmpResult"
	# 重定向结果文件
	popenLog("ls " + sqlDir + " > tmpResult")

	# 版本号列表 中间跨度版本的sql都需要执行
	versionNumList=getExecResultStrV(tmpResult)

	nowSwVersion += ".sql"
	needSwVersion += ".sql"

	clearNoNeedVerList(versionNumList, nowSwVersion, needSwVersion)
	sqlRun =""
	# 对于每一个版本的sql脚本
	for i in versionNumList:
		if ""==i:
			# 跳过区间外的版本
			continue

		sqlRun = sqlRun + "mysql -h" + srvIP + " -ushengli -pshengli0 < " + i
		popenLog("cat " + i)
		popenLog( str=sqlRun)

def getExecResultStrV(file=""):
	resultLineV=[""]
	fileOpen=open(file, mode="r")
	lines = fileOpen.readlines()
	for line in lines:
		resultLineV.append(line)
	return resultLineV

def findKeyInfo(resultLineV=[""], key=""):
	for line in resultLineV:
		index = line.find(key)
		if index > 0:
			return index 
	return -1

def clearNoNeedVerList(resultLineV = [""], nowVer="", needVer=""):
	# 不同系列的版本号比较ascii 认为 one > 4.xx ultra > 3.xx，当前大版本号变更符合这个逻辑
	if(nowVer < needVer):
		# 判断为版本升级
		for ver in resultLineV:
			# 正常的版本号比较           # 正常情况下不会出现
			if(nowVer <= nowVer or nowVer > needVer):
				nowVer = ""

	if nowVer > needVer:
		# 判断为版本回退
		for ver in resultLineV:
			# 理论上不会出现			 # 正常的版本号比较
			if(nowVer > nowVer or nowVer <= needVer):
				nowVer = ""


run()
